<?php
class UserModel
{
    private $user_db;

    public function __construct()
    {
        $this->user_db = new UserDb();
    }

    public function encryptToken($user_id)
    {
        $app_conf = ConfLib::get('app', 'app');
        $deadline = time() + $app_conf['access_token_ttl'];
        return md5($user_id . $app_conf['secret'] . $deadline) . '-' . $app_conf['id'] . '-' . $user_id . '-' . $deadline;
    }

    public static function decryptToken($token)
    {
        $app_conf = ConfLib::get('app', 'app');
        $tmp = explode('-', $token);
        if((md5($tmp[2] . $app_conf['secret'] . $tmp[3]) == $tmp[0]) && ($tmp[3]>time())) {
            return array(
                'app_id' => $tmp[1],
                'user_id' => $tmp[2],
            );
        } else {
            return false;
        }
    }

    public function getToken($partner_name, $code)
    {
        $partner_user_model = new PartnerUserModel($partner_name);
        $user = $partner_user_model->getMe($code);
        $user_id = $partner_user_model->setUser($user);
        return $this->encryptToken($user_id);
    }

    public function get($id)
    {
        $where = array(
            'e' => array(
                'id' => $id,
            ),
        );
        return $this->user_db->selectRow($where);
    }
}
?>
